import path from 'path';
import os from 'os';
import chalk from 'chalk';
import webpack from 'webpack';
const { DefinePlugin } = webpack;
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import CopyWebpackPlugin from 'copy-webpack-plugin';
// import ESLintPlugin from 'eslint-webpack-plugin';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';

const __dirname = path.resolve();

function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name in interfaces) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        return iface.address; // 返回本地 IPv4 地址
      }
    }
  }
  return 'localhost';
}

function printServerInfo(devServer) {
  const localIP = getLocalIP();
  const port = devServer.port;

  console.log(chalk.green('\n  Development Server running at:'));
  console.log(chalk.cyan(`  - Local:   http://localhost:${port}`));
  console.log(chalk.cyan(`  - Network: http://${localIP}:${port}\n`));
}

const isProduction = process.env.NODE_ENV === 'production';

export default {
  mode: isProduction ? 'production' : 'development',
  entry: {
    app: './src/renderer/index.tsx',
  },
  devtool: isProduction ? 'source-map' : 'eval-source-map', // 生产环境不需要 source map
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].[contenthash].js',
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, 'src'),
      '@pages': path.resolve(__dirname, 'src/renderer/pages'),
      '@components': path.resolve(__dirname, 'src/renderer/components'),
      '@assets': path.resolve(__dirname, 'src/renderer/assets'),
      '@images': path.resolve(__dirname, 'src/renderer/assets/images'),
      '@store': path.resolve(__dirname, 'src/renderer/store'),
      '@router': path.resolve(__dirname, 'src/renderer/router'),
      '@api': path.resolve(__dirname, 'src/renderer/api'),
      '@hooks': path.resolve(__dirname, 'src/renderer/hooks'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@types': path.resolve(__dirname, 'src/types'),
    },
    extensions: ['.tsx', '.ts', '.js', '.jsx', '.json'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-react',
              '@babel/preset-typescript',
            ],
          },
        },
      },
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/],
        },
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash].css',
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      minify: isProduction,
    }),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'public'),
          to: path.resolve(__dirname, 'dist'),
          globOptions: {
            ignore: ['**/index.html', '**/*.html'],
          },
          noErrorOnMissing: true,
        },
      ],
    }),
    // new ESLintPlugin({
    //   context: path.resolve(__dirname, 'src'),
    //   extensions: ['js', 'jsx', 'ts', 'tsx'],
    //   emitWarning: !isProduction,
    // }),
    new ForkTsCheckerWebpackPlugin({
      async: false,
      typescript: {
        configFile: path.resolve(__dirname, 'tsconfig.json'),
      },
    }),
    new DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
        PORT: process.env.PORT || 8003,
      },
    }),
    // new ProgressBarPlugin({
    //   format: ` project build [:bar] ${chalk.green.bold(':percent')} (:elapsed seconds)`,
    //   clear: true,        // 完成后清除进度条
    //   customSymbol: '✔',  // 自定义完成符号
    // }),
    {
      apply: (compiler) => {
        compiler.hooks.done.tap('PrintServerInfoPlugin', (stats) => {
          if (stats.hasErrors()) return;

          // 获取devServer实例
          const devServer = compiler.options.devServer;
          // HMR 构建（热更新）后清除
          // const output = stats.toString({ colors: false });
          // const lines = output.trim().split('\n');
          // console.log('lines', lines);
          if (devServer) {
            printServerInfo(devServer);
          }
        });
      }
    }
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 8003,
    hot: true,
    historyApiFallback: true, // 支持 HTML5 History API, 所有未匹配的请求都重定向到 index.html
    devMiddleware: {
      stats: 'minimal'  // 开发中间件的输出级别
    },
    setupMiddlewares: (middlewares, devServer) => {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }

      // 初始启动时打印
      if (devServer.options) {
        printServerInfo(devServer.options);
      }
      return middlewares;
    },
  },
  stats: {
    all: false,       // 禁用所有输出
    modules: false,   // 禁用模块信息
    errors: true,     // 只显示错误
    warnings: true,   // 只显示警告
    moduleTrace: false,
    errorDetails: false
  }
};